# -*- coding: utf-8 -*-
from django.shortcuts import render,get_object_or_404, render_to_response
from django.http import HttpResponseRedirect,HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext, loader
from clients.models import Client
from django.utils import simplejson 
import re, json   

# Create your views here.
def autocompletion(request):
    if request.is_ajax():
        q = request.GET.get('term', '')   
        listeCl = Client.objects.filter(nom__istartswith=q)
        results = []
        for e in listeCl:
            tab_rep = {}
            tab_rep['id'] = e.id
            tab_rep['label'] = e.nom

            results.append(tab_rep)
        data = simplejson.dumps(results)
    else:
        data = 'fail'
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)

def search_poudre(request): 
    if request.is_ajax():
        q = request.GET.get('term', '')  
        question = re.sub(r'_', " ", q);
        p = get_object_or_404(Client,nom__exact=question)
        listeE = p.event_set.all()
        results = []
        for event in listeE:
            tab_infoE = {}
            tab_infoE['id'] = event.id
            tab_infoE['TE'] = event.TE.__unicode__()
            # tab_infoE['date'] = event.date
            
            results.append(tab_infoE)
        data = simplejson.dumps(results)
    else:
        data = 'fail'
    """E = event.__unicode__()
            message = message + E 
    if message == None or message == "":
        message = 'Chưa nhập tên bột hoặc bột không hiện hữu'
    return HttpResponse("Message : "+message)"""
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)
